<template>
  <view>
    <!-- 手动设置倒计时组件 -->
    <CountdownController class="CountdownController"
      @startManualCountdown="handleStartOrStopManualCountdown"
      @stopManualCountdown="handleStartOrStopManualCountdown"
      @manualCountdownEnded="handleManualCountdownEnded"
      ref="countdownController"
      :key="componentKey"
    />
    <RadioChange></RadioChange>
    <!-- 新增 TimingComponent 组件 -->
    <TimingComponent></TimingComponent>
  </view> 
</template>

<script>
import CountdownController from '@/component/CountdownController.vue';
import RadioChange from '@/component/RadioChange.vue';
import TimingComponent from '@/component/TimingComponent.vue'; // 导入 TimingComponent 组件
import {save} from '@/api/countdown.js';

export default {
  components: {
    CountdownController,
    RadioChange,
    TimingComponent // 注册 TimingComponent 组件
  },
  data() {
    return {
      // 倒计时
      countdown: { days: 0, hours: 0, minutes: 10, seconds: 0 },
      // 投票状态
      isVotingEnded: false,
      // 提示消息
      showToast: false,
      toastType: 'success',
      toastMessage: '',
      // 用于标记是否可以保存倒计时数据
      canSaveCountdown: true,
      // 用于控制组件重新渲染的 key
      componentKey: 1
    };
  },
  methods: {
    // 处理手动开始或停止倒计时
    async handleStartOrStopManualCountdown(newCountdown) {
      if (!this.canSaveCountdown) {
        this.showToastMessage('warning', '当前不能保存倒计时，请稍后再试');
        return;
      }
      this.countdown = newCountdown;
      console.log(newCountdown);
      try {
        this.canSaveCountdown = false; // 防止重复保存
        // 调用后端接口保存倒计时数据
        const response = await save(newCountdown);
        console.log(response);
        this.canSaveCountdown = true; // 保存成功后恢复可保存状态
        if (response) {
          // 重置页面数据
          this.resetPageData();
          // 设置新的倒计时数据
          this.countdown = newCountdown;
          // 更新 key 值，触发组件重新渲染
          this.componentKey++;
        }
      } catch (error) {
        console.error('保存倒计时数据失败:', error);
        this.canSaveCountdown = true; // 保存失败后恢复可保存状态
      }
    },
    // 处理手动倒计时结束
    handleManualCountdownEnded() {
      this.isVotingEnded = true;
      this.showToastMessage('info', '手动设置的投票已结束，感谢参与');
    },
    // 显示提示消息
    showToastMessage(type, message) {
      this.toastType = type;
      this.toastMessage = message;
      this.showToast = true;

      setTimeout(() => {
        this.showToast = false;
      }, 2000);
    },
    // 重置页面数据
    resetPageData() {
      this.countdown = { days: 0, hours: 0, minutes: 0, seconds: 0 };
      this.isVotingEnded = false;
      this.showToast = false;
      this.toastType = 'success';
      this.toastMessage = '';
    }
  }
};
</script>

<style scoped>
.CountdownController{
  background-color: #999;
}
/* 可以添加样式 */
</style>